package cn.itcast.star.graph.core.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.itcast.star.graph.core.pojo.User;
import org.springframework.stereotype.Component;

/**
 * JWT工具类
 */
@Component
public class JwtUtil {

    static final String KEY = "FK";

    /**
     * 生成token
     */
    public static String genToken(User user) {
        return JWT.create()
                .setPayload("uid", user.getId())
                .setPayload("username", user.getUsername())
                .setExpiresAt(DateTime.now().offsetNew(DateField.YEAR,1))
                .setKey(KEY.getBytes())
                .sign();
    }

    /**
     * 验证token
     */
    public static boolean verify(String token) {
        try {
            return JWT.of(token).setKey(KEY.getBytes()).verify();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从token获取用户信息
     */
    public static User getUser(String token) {
        JWT jwt = JWT.of(token).setKey(KEY.getBytes());
        if (jwt != null && jwt.getPayloads() != null) {
            return User.builder()
                    .id(jwt.getPayload("uid") == null ? null : NumberUtil.parseLong(jwt.getPayload("uid").toString()))
                    .username(StrUtil.toString(jwt.getPayload("username")))
                    .build();
        }
        return null;
    }


}

